from itsdangerous import TimedJSONWebSignatureSerializer as  Serializer,BadSignature

from django.conf import settings
from oauth.models import OAuthQQUser
"""
几行代码实现某个功能 ，可以抽取为一个函数（方法）
二次复写的代码就之中界抽取封装
"""
def generic_openid_token(openid):
    """
    生成保存用户数据的token
    :param openid: 用户的openid
    :return: token
    """
    serializer = Serializer(settings.SECRET_KEY, 3600)
    #对openid进行处理，返回二进制
    token = serializer.dumps({'openid':openid})
    openid_token = token.decode()
    return openid_token



def check_openid_token(access_token):

    s = Serializer(settings.SECRET_KEY, 3600)

    # loads 存在 过期 或者被篡改的异常
    try:
        data = s.loads(access_token)
    except BadSignature as e:
        return None
    else:
        openid = data.get('openid')

    return openid